<template>
	<el-dialog
	  title="手工导入稳考计划"
	  :visible.sync="visible"
	  :before-close="close"
	  width="80%">
    <!-- 货品 -->
    <el-row>
      <el-col :span="plans.length == 1 ? 24 : plans.length == 2 ? 12 : 8" v-for="(p,i) in plans" :key="i">
        <el-card >
          <div>
            <el-button type="primary" size="small" class="pan-btn primary-btn" @click="showProductSelect(i)">{{ p.productId != null ? '重新选择' : '选择货品' }}</el-button>
            <div style="float: right;">
              <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-plus" @click="copy(i)" circle size="mini" />
              <el-button  v-if="plans.length > 1" type="danger" class="pan-btn danger-btn" icon="el-icon-minus" @click="plans.splice(i,1)" circle size="mini" />
            </div>
          </div>

          <el-form v-if="p.productId != null" label-width="80px">
            <el-form-item label="货品编号:">
              {{ p.productId }}
            </el-form-item>

            <el-form-item label="货品分类:">
              {{ p.productCategoryName }}
            </el-form-item>

            <el-form-item label="货品名称:">
              {{ p.productName }}
            </el-form-item>

            <el-form-item label="物料编码:">
              {{ p.productGmp }}
            </el-form-item>

            <el-form-item label="货品规格:">
              <span v-html="p.productSpec" />
            </el-form-item>

            <el-form-item label="生产车间:">
              {{ p.workshopName }}
            </el-form-item>

            <el-form-item label="存样日期:">
              <el-date-picker
                v-model="p.storeDate"
                :clearable="false"
                @change="setStoreDate(i)"
                align="right"
                type="date"
                placeholder="存样日期"
                :picker-options="pickerOptions"
                style="width: 100%;"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                size="small">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="考察方式:" v-if="p.storeDate != null && p.storeDate != ''">
              <el-select @change="setStabilityMode(i)" value-key="stabilityModeId" v-model="p.stabilityMode" placeholder="考察方式" style="width: 100%" size="small">
                <el-option v-for="m in modeList" :key="m.stabilityModeId" :label="m.stabilityModeName" :value="m" />
              </el-select>
            </el-form-item>

            <el-form-item label="时间单位:" v-if="typeof p.stabilityMode == 'object'">
              <el-select @change="setCheckPeriodTime(i)" value-key="timeId" v-model="p.checkPeriodTime" placeholder="时间单位" style="width: 100%" size="small">
                <el-option v-for="t in timeList" :key="t.timeId" :label="t.timeName" :value="t" />
              </el-select>
            </el-form-item>

            <el-form-item label="考察时间:" v-if="typeof p.stabilityMode == 'object'">
              <el-tag
                :key="j"
                v-for="(t,j) in p.times"
                closable
                @close="deleteTime(i,j)">
                {{ t.timeValue }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="p.inputVisible"
                v-model="p.inputValue"
                size="small"
                @keyup.enter.native="addTime(i)"
                @blur="addTime(i)">
              </el-input>
              <el-button v-else size="small" class="button-new-tag" @click="showInput(i)">+</el-button>
            </el-form-item>

            <el-form-item label="货品规格:">
              <div v-if="productPackSpecList.length == 0" style="color: #F56C6C;">请添加此货品的包装规格</div>
              <el-select v-else v-model="p.productPackSpec" placeholder="包装规格" style="width: 100%" size="small">
                <el-option v-for="item in productPackSpecList" :key="item.productPackSpecId" :label="item.productPackSpec" :value="item.productPackSpec" />
              </el-select>
            </el-form-item>

            <el-form-item label="批号:">
              <span slot="label">批&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</span>
              <el-input v-model="p.batchNum" size="small" placeholder="批号" />
            </el-form-item>

            <el-form-item label="生产日期:">
              <el-date-picker
                v-model="p.productionDate"
                align="right"
                type="date"
                :clearable="false"
                @change="setValidity(i)"
                placeholder="生产日期"
                :picker-options="pickerOptions"
                style="width: 100%;"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                size="small">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="有效期至:">
              <el-date-picker
                v-model="p.validityDate"
                align="right"
                type="date"
                :clearable="false"
                placeholder="有效期至"
                style="width: 100%;"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss"
                size="small">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="存样位置:">
              <el-input v-model="p.storeLocation" size="small" placeholder="存样位置" />
            </el-form-item>

            <el-form-item label="小入库量:">
              <el-input @change="setIncomingMini(i)" v-model="p.incomingMini" placeholder="数值" size="small">
                <el-select @change="setIncomingMiniUnit(i)" value-key="unitId" v-model="p.incomingMiniUnit" slot="append" placeholder="单位" style="width: 100px;">
                  <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item" />
                </el-select>
              </el-input>
            </el-form-item>

            <el-form-item label="大入库量:">
              <el-input @change="setIncomingBig(i)" v-model="p.incomingBig" placeholder="数值" size="small">
                <el-select @change="setIncomingBigUnit(i)" value-key="unitId" v-model="p.incomingBigUnit" slot="append" placeholder="单位" style="width: 100px;">
                  <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item" />
                </el-select>
              </el-input>
            </el-form-item>

          </el-form>
        </el-card>
      </el-col>
    </el-row>

	  <span slot="footer" class="dialog-footer">
      <el-button @click="close" type="primary" size="small" class="pan-btn primary-btn">取 消</el-button>
      <el-button :loading="submiting" @click="submit" type="success" class="pan-btn success-btn" size="small">提 交</el-button>
  	</span>

    <product-select
      @getProduct="getProduct"
      @showProductSelect="closeInner('productSelectVisible')"
      :childDataForm="childDataForm"
      v-if="productSelectVisible" />

	</el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
	import { CODE_OK } from '@/common/js/config'
	import { isBlank,parseTime } from '@/common/js/utils'
  import { isPositiveNumber,isPositiveIntegerNumber } from '@/common/js/validate'
  import ProductSelect from '@/views/modules/base/product-select'
  import { getStabilityModeList,getBaseTimeList,getModeTimeList,importPlans } from '@/api/stability'
  import { getUnitList } from '@/api/check'
  import { getProductPackSpecsByProductId } from '@/api/product'
	export default {
		data() {
			return {
				visible: false,
        productSelectVisible: false,
        productPackSpecList: [],
        unitList: [],
        modeList: [],
        timeList: [],
        waiteIndex: '',
        submiting: false,
        plans: [{
          planName: null,
          workshopId: null,
          workshopName: null,
          productionDate: null,
          validityDate: null,
          productId: null,
          productGmp: null,
          productName: null,
          productSpec: null,
          productValidity: null,
          productPackSpec: null,
          batchNum: null,
          inventoryUnitId: null,
          inventoryUnitName: null,
          incomingMini: null,
          incomingMiniUnitId: null,
          incomingMiniUnitName: null,
          incomingBig: null,
          incomingBigUnitId: null,
          incomingBigUnitName: null,
          storeDate: null,
          storeLocation: null,
          stabilityModeId: null,
          stabilityModeName: null,
          times: [],
          inputVisible: false,
          inputValue: null
        }],
        childDataForm: ''
			}
		},
    components: {
      ProductSelect
    },
		created() {
      this.getInfo()
      this.visible = true
    },
    computed: {
      ...mapGetters([
         'userInfo'
      ])
    },
		methods: {
      submit() {
        if (this.formVerify()) {
          this.plans = this.plans.map(p => {
            this.$set(p,'planName',p.productName + '(' + p.batchNum + ')【' + p.stabilityModeName + '】')
            this.$set(p,'total',p.times.length)
            this.$set(p,'now',0)
            return p
          })
          this.submiting = true
          importPlans(this.plans).then(res => {
            if (res.code === CODE_OK) {
              this.$message.success('提交成功')
              this.close('submit')
            }else{
              this.$message.error(res.msg)
            }
            this.submiting = false
          })
        }
      },
      formVerify() {
        for (let p of this.plans) {
          if (isBlank(p.productId)) {
            this.$message.error('请选择货品')
            return false
          }
          if (isBlank(p.storeDate)) {
            this.$message.error('存样日期不能为空')
            return false
          }
          if (isBlank(p.stabilityModeId)) {
            this.$message.error('考察方式不能为空')
            return false
          }
          if (isBlank(p.checkPeriodTimeId)) {
            this.$message.error('时间单位不能为空')
            return false
          }
          if (p.times.length == 0) {
            this.$message.error('考察时间不能为空')
            return false
          }
          if (isBlank(p.batchNum)) {
            this.$message.error('批号不能为空')
            return false
          }
          if (isBlank(p.incomingMini) || isBlank(p.incomingMiniUnitId)) {
            this.$message.error('小入库量及单位不能为空')
            return false
          }
          if (isBlank(p.incomingBig) || isBlank(p.incomingBigUnitId)) {
            this.$message.error('大入库量及单位不能为空')
            return false
          }
        }
        return true
      },
      timeMap(key) {
        const map = {
          '分': 'm',
          '时': 'h',
          '日': 'd',
          '周': 'w',
          '月': 'M',
          '年': 'y'
        }
        return map[key]
      },
      addTime(i) {
        let inputValue = this.plans[i].inputValue
        if (!isPositiveNumber(inputValue)) {
          this.$message.error('请输入正数')
          return
        }
        let tt =  this.plans[i].times.find(v => {return v.timeValue == inputValue})
        if (typeof tt == 'object') {
          this.$message.error('不允许有重复')
          this.plans[i].inputVisible = false
          this.plans[i].inputValue = null
          return
        }
        let t = {
          timeValue: inputValue,
          timeId: this.plans[i].checkPeriodTimeId,
          timeName: this.plans[i].checkPeriodTimeName,
          beginTimePoint: null,
          timePoint: null,
          endTimePoint: null
        }
        if (isPositiveIntegerNumber(inputValue)) {
          t.timePoint = this.moment(this.plans[i].storeDate).add(t.timeValue, this.timeMap(t.timeName)).format('YYYY-MM-DD HH:mm:ss')
          t.beginTimePoint = this.moment(t.timePoint).subtract(15, 'd').format('YYYY-MM-DD HH:mm:ss')
          t.endTimePoint = this.moment(t.timePoint).add(15, 'd').format('YYYY-MM-DD HH:mm:ss')
        }
        this.plans[i].times.push(t)
        this.plans[i].inputVisible = false
        this.plans[i].inputValue = null
      },
      deleteTime(i,j) {
        if (this.plans[i].times.length == 1) {
          this.$message.error('至少保留一个时间')
          return
        }
        this.plans[i].times.splice(j,1)
      },
      showInput(i) {
        this.plans[i].inputVisible = true
      },
      setStoreDate(i) {
        this.plans[i].times = this.plans[i].times.map(t => {
          t.timePoint = this.moment(this.plans[i].storeDate).add(t.timeValue, this.timeMap(t.timeName)).format('YYYY-MM-DD HH:mm:ss')
          t.beginTimePoint = this.moment(t.timePoint).subtract(15, 'd').format('YYYY-MM-DD HH:mm:ss')
          t.endTimePoint = this.moment(t.timePoint).add(15, 'd').format('YYYY-MM-DD HH:mm:ss')
          return t
        })
      },
      setStabilityMode(i) {
        this.plans[i].stabilityModeId = this.plans[i].stabilityMode.stabilityModeId
        this.plans[i].stabilityModeName = this.plans[i].stabilityMode.stabilityModeName
        this.getTimeData(i)
      },
      getTimeData(i) {
        this.plans[i].times = []
        const params = {
          stabilityModeId: this.plans[i].stabilityModeId
        }
        getModeTimeList(params).then(res => {
          if (res.code === CODE_OK) {
            this.plans[i].times = res.list.map(t => {
              t.timePoint = this.moment(this.plans[i].storeDate).add(t.timeValue, this.timeMap(t.timeName)).format('YYYY-MM-DD HH:mm:ss')
              t.beginTimePoint = this.moment(t.timePoint).subtract(15, 'd').format('YYYY-MM-DD HH:mm:ss')
              t.endTimePoint = this.moment(t.timePoint).add(15, 'd').format('YYYY-MM-DD HH:mm:ss')
              return t
            })
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      setCheckPeriodTime(i) {
        this.plans[i].checkPeriodTimeId = this.plans[i].checkPeriodTime.timeId
        this.plans[i].checkPeriodTimeName = this.plans[i].checkPeriodTime.timeName
      },
      setIncomingMini(i) {
        if (!isPositiveNumber(this.plans[i].incomingMini)) {
          this.$message.error('请输入正数值类型')
          this.plans[i].incomingMini = null
          return
        }
        this.plans[i].incomingBig = this.plans[i].incomingMini
      },
      setIncomingMiniUnit(i) {
        this.$message.warning("注意，系统默认此单位为实际取样量单位")
        let id = this.plans[i].incomingMiniUnit.unitId
        let name = this.plans[i].incomingMiniUnit.unitName
        this.plans[i].incomingMiniUnitId = id
        this.plans[i].incomingMiniUnitName = name
        this.plans[i].inventoryUnitId = id
        this.plans[i].inventoryUnitName = name
        this.plans[i].inventoryUnit = {
          unitId: id,
          unitName: name
        }
        if (this.plans[i].times.length > 0) {
          this.plans[i].times = this.plans[i].times.map(t => {
            t.getUnitId = id
            t.getUnitName = name
            return t
          })
        }
        if (isBlank(this.plans[i].incomingBigUnitId)) {
          this.plans[i].incomingBigUnit = {
            unitId: id,
            unitName: name
          }
          this.plans[i].incomingBigUnitId = id
          this.plans[i].incomingBigUnitName = name
        }
      },
      setIncomingBig(i) {
        if (!isPositiveNumber(this.plans[i].incomingBig)) {
          this.$message.error('请输入正数值类型')
          this.plans[i].incomingBig = null
        }
      },
      setIncomingBigUnit(i) {
        this.plans[i].incomingBigUnitId = this.plans[i].incomingBigUnit.unitId
        this.plans[i].incomingBigUnitName = this.plans[i].incomingBigUnit.unitName
      },
      copy(i) {
        this.plans.push(JSON.parse(JSON.stringify(this.plans[i])))
      },
      showProductSelect(i) {
        this.waiteIndex = {
          i: i
        }
        this.childDataForm = {
          isMultiple: false,
          isStability: true
        }
        this.productSelectVisible = true
      },
      getProduct(p) {
        let i = this.waiteIndex.i
        this.plans[i].productCategoryName = p.productCategoryName
        this.plans[i].productId = p.productId
        this.plans[i].productGmp = p.productGmp
        this.plans[i].productName = p.productName
        this.plans[i].productSpec = p.productSpec
        this.plans[i].productValidity = p.productValidity
        this.plans[i].productPackSpec = ''
        this.plans[i].workshopId = p.workshopId
        this.plans[i].workshopName = p.workshopName
        this.product = p
        const params = {
          productId: p.productId
        }
        getProductPackSpecsByProductId(params).then(res => {
          if (res.code === CODE_OK) {
            this.productPackSpecList = res.productPackSpecs
            if (this.productPackSpecList.length == 0) {
              this.$message.error("请联系QA管理员(肖慧)添加此货品的包装规格")
            }
          }else{
            this.$message.error(res.msg)
          }
        })
        this.waiteIndex = ''
      },
      setValidity(i) {
        if (!isBlank(this.plans[i].productValidity)) {
			this.plans[i].validityDate = this.calcValidity(this.plans[i].productionDate,this.plans[i].productValidity)
        }
      },
      closeInner(prop) {
        this[prop] = false
        this.childDataForm = ''
      },
      getInfo() {
        getUnitList().then(res => {
          if (res.code === CODE_OK) {
            this.unitList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getStabilityModeList().then(res => {
          if (res.code === CODE_OK) {
            this.modeList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getBaseTimeList().then(res => {
          if (res.code === CODE_OK) {
            this.timeList = res.list
            let monT = this.timeList.find(v => {return v.timeName === '月'})
            if (typeof monT == 'object') {
              this.plans = this.plans.map(p => {
                this.$set(p,'checkPeriodTime', {
                  timeId: monT.timeId,
                  timeName: monT.timeName
                })
                this.$set(p,'checkPeriodTimeId', monT.timeId)
                this.$set(p,'checkPeriodTimeName', monT.timeName)
                return p
              })
            }
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      close(val) {
        this.visible = false
        if (val == 'submit') {
          this.$emit('submit')
        }
        this.$emit('close')
      },
    }
	}
</script>

<style scoped>
  >>> .el-form-item__content .el-input-group {
    vertical-align: middle !important;
  }
  >>> .el-form-item__content {
    line-height: 40px !important;
  }
  >>> .el-form-item {
    margin-bottom: 0px !important;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
